package org.event.core.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.event.core.enums.KafkaSendEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangjm
 * @date 2023年11月29日 10:58
 */
@Configuration
@EnableKafka
public class KafkaProducerConfig {


    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    public KafkaProducerConfig() {
        System.out.println("kafka--------------------------------生产配置");
    }

    /**
     * 创建生产值消息工厂
     */
    @Bean
    public ProducerFactory<Integer, String> producerFactory() {
        return new DefaultKafkaProducerFactory(producerProperties());
    }

    /**
     * 生产基本配置
     */
    @Bean
    public Map<String, Object> producerProperties() {
        Map<String, Object> props = new HashMap<String, Object>();
        //设置kafka访问地址
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        //消息转化
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //重试次数
        props.put(ProducerConfig.RETRIES_CONFIG, 1);
        //分批处理内存设置
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 1048576);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        //使用内存配置
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432L);
        //确认标志符使用配置
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        return props;
    }

    @Bean
    public KafkaTemplate<Integer, String> kafkaTemplate() {
        KafkaTemplate kafkaTemplate = new KafkaTemplate<Integer, String>(producerFactory(), true);
        kafkaTemplate.setDefaultTopic(KafkaSendEnum.ALARM_WARN_PUSH.getTopic());
        return kafkaTemplate;
    }


}
